package com.itheima.exerciseTest.method20_29.method28;

import java.util.concurrent.atomic.AtomicInteger;

// 柜台类
public class Counter implements Runnable {
    private Warehouse wh;

    public Counter(Warehouse wh) {
        this.wh = wh;
    }

    // 创建原子类
    AtomicInteger ai = new AtomicInteger();

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (wh){
            if (wh.getTickets() <= 0) {
                break;
            }
            try {
                System.out.print("正在买票...");
                Thread.sleep(300);
                ai.getAndSet(wh.getTickets());
                wh.setTickets(ai.decrementAndGet());
                System.out.println(Thread.currentThread().getName() + "买票完成，还剩" + ai.get() + "张票");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            }
        }
    }
}
